<template>
  <div style="display: flex; flex-direction: column;">
    <el-button type="primary" @click="openAddDialog" style="margin-bottom: 0px; margin-left: auto;">新增企业</el-button>

    <el-table :data="companies" style="width: 100%; table-layout: fixed;">
      <el-table-column prop="name" label="公司名称" :min-width="200" align="center" header-align="center"></el-table-column>
      <el-table-column prop="legal_person" label="法人" :min-width="200" align="center"
        header-align="center"></el-table-column>
      <el-table-column prop="address" label="地址" :min-width="200" align="center"
        header-align="center"></el-table-column>

      <el-table-column label="操作" :min-width="200" align="center" header-align="center">
        <template v-slot="scope">
          <el-button @click="viewDetails(scope.row)" size="small" type="primary" icon="el-icon-view"
            class="action-button">详情</el-button>
          <el-button @click="editCompany(scope.row)" size="small" type="warning" icon="el-icon-edit"
            class="action-button">编辑</el-button>
          <el-button @click="deleteCompany(scope.row)" size="small" type="danger" icon="el-icon-delete"
            class="action-button">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!-- 详情模态框 -->
    <el-dialog v-model="isDetailDialogVisible" title="企业详情" width="600px" :lock-scroll="false">
      <div v-if="selectedCompany" class="company-details">
        <el-row class="detail-row" v-for="(value, key) in selectedCompany" :key="key">
          <el-col :span="8" class="detail-label">{{ formatLabel(key) }}:</el-col>
          <el-col :span="16">{{ formatValue(key, value) }}</el-col>
        </el-row>
      </div>
      <template #footer>
        <el-button @click="isDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增企业模态框 -->
    <el-dialog v-model="isAddDialogVisible" title="新增企业" width="500px" :lock-scroll="false">
      <el-form label-width="100px">
        <el-form-item label="公司名称">
          <el-input v-model="newEnterprise.name"></el-input>
        </el-form-item>
        <el-form-item label="行业">
          <el-input v-model="newEnterprise.industry"></el-input>
        </el-form-item>
        <el-form-item label="信用代码">
          <el-input v-model="newEnterprise.credit_code"></el-input>
        </el-form-item>
        <el-form-item label="注册资本">
          <el-input v-model="newEnterprise.registered_capital" type="number"></el-input>
        </el-form-item>
        <el-form-item label="法人">
          <el-input v-model="newEnterprise.legal_person"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="newEnterprise.address"></el-input>
        </el-form-item>
        <el-form-item label="成立日期">
          <el-date-picker v-model="newEnterprise.establish_date" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isAddDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addEnterprise">确认新增</el-button>
      </template>
    </el-dialog>

    <!-- 编辑企业模态框 -->
<el-dialog v-model="isEditDialogVisible" title="编辑企业" width="500px" :lock-scroll="false">
  <el-form label-width="100px">
    <el-form-item label="公司名称">
      <el-input v-model="editEnterprise.name"></el-input>
    </el-form-item>
    <el-form-item label="行业">
      <el-input v-model="editEnterprise.industry"></el-input>
    </el-form-item>
    <el-form-item label="信用代码">
      <el-input v-model="editEnterprise.credit_code"></el-input>
    </el-form-item>
    <el-form-item label="注册资本">
      <el-input v-model="editEnterprise.registered_capital" type="number"></el-input>
    </el-form-item>
    <el-form-item label="法人">
      <el-input v-model="editEnterprise.legal_person"></el-input>
    </el-form-item>
    <el-form-item label="地址">
      <el-input v-model="editEnterprise.address"></el-input>
    </el-form-item>
    <el-form-item label="成立日期">
      <el-date-picker v-model="editEnterprise.establish_date" type="date" placeholder="选择日期"></el-date-picker>
    </el-form-item>
  </el-form>
  <template #footer>
    <el-button @click="isEditDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="updateEnterprise">确认更新</el-button>
  </template>
</el-dialog>

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { ElMessageBox } from 'element-plus';

const companies = ref([]);
const isDetailDialogVisible = ref(false);
const isAddDialogVisible = ref(false);
const selectedCompany = ref(null);
const newEnterprise = ref({
  name: '',
  industry: '',
  credit_code: '',
  registered_capital: '',
  legal_person: '',
  address: '',
  establish_date: ''
});

const isEditDialogVisible = ref(false);
const editEnterprise = ref({
  id: '',
  name: '',
  industry: '',
  credit_code: '',
  registered_capital: '',
  legal_person: '',
  address: '',
  establish_date: ''
});

const editCompany = (company) => {
  // 复制选中的公司信息到编辑表单
  editEnterprise.value = { ...company };
  isEditDialogVisible.value = true;
};

const updateEnterprise = async () => {
  let formattedDate = '';
  const establishDate = editEnterprise.value.establish_date;

  if (establishDate instanceof Date) {
    formattedDate = establishDate.toISOString().split('T')[0];
  } else if (typeof establishDate === 'string') {
    const dateParts = establishDate.split('T')[0];
    if (dateParts) {
      formattedDate = dateParts;
    } else {
      console.error('日期格式错误');
      return;
    }
  } else {
    console.error('不支持的日期格式');
    return;
  }

  const updatedEnterpriseData = {
    ...editEnterprise.value,
    establish_date: formattedDate
  };

  try {
    const response = await axios.put(`http://localhost:3000/admin/enterprises/${editEnterprise.value.id}`, updatedEnterpriseData);
    ElMessage.success('企业信息更新成功！');
    isEditDialogVisible.value = false;
    fetchCompanies();
  } catch (error) {
    console.error('企业信息更新失败:', error);
  }
};

const fetchCompanies = async () => {
  try {
    const response = await axios.get('http://localhost:3000/admin/enterprises');
    companies.value = response.data;
  } catch (error) {
    console.error('获取企业列表失败:', error);
  }
};

onMounted(fetchCompanies);

const openAddDialog = () => {
  isAddDialogVisible.value = true;
};

//增企业
const addEnterprise = async () => {
  let formattedDate = '';
  const establishDate = newEnterprise.value.establish_date;

  if (establishDate instanceof Date) {
    formattedDate = establishDate.toISOString().split('T')[0];
  } else if (typeof establishDate === 'string') {
    const dateParts = establishDate.split('T')[0];
    if (dateParts) {
      formattedDate = dateParts;
    } else {
      console.error('日期格式错误');
      return;
    }
  } else {
    console.error('不支持的日期格式');
    return;
  }

  const enterpriseData = {
    name: newEnterprise.value.name,
    industry: newEnterprise.value.industry,
    credit_code: newEnterprise.value.credit_code,
    registered_capital: newEnterprise.value.registered_capital,
    legal_person: newEnterprise.value.legal_person,
    address: newEnterprise.value.address,
    establish_date: formattedDate
  };

  try {
    const response = await axios.post('http://localhost:3000/admin/enterprises', enterpriseData);
    ElMessage.success('企业新增成功！');
    isAddDialogVisible.value = false;
    fetchCompanies();
  } catch (error) {
    console.error('企业添加失败:', error);
  }
};

//查看详情
const viewDetails = (company) => {
  selectedCompany.value = company;
  isDetailDialogVisible.value = true;
};

const deleteCompany = async (company) => {
  try {
    // 二次确认弹框
    await ElMessageBox.confirm(
      `确定要删除企业 "${company.name}" 吗？此操作不可撤销！`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 用户确认后执行删除
    await axios.delete(`http://localhost:3000/admin/enterprises/${company.id}`);

    // 过滤掉被删除的企业，更新界面
    companies.value = companies.value.filter(item => item.id !== company.id);

    // 成功提示
    ElMessage.success('企业删除成功！');
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除企业失败:', error);
      ElMessage.error('删除失败，请稍后重试');
    }
  }
};

// 格式化显示标签
const formatLabel = (key) => {
  switch (key) {
    case 'name': return '公司名称';
    case 'industry': return '行业';
    case 'credit_code': return '信用代码';
    case 'registered_capital': return '注册资本';
    case 'legal_person': return '法人';
    case 'address': return '地址';
    case 'establish_date': return '成立日期';
    default: return key;
  }
};

// 格式化显示值
const formatValue = (key, value) => {
  if (key === 'establish_date') {
    return new Date(value).toLocaleDateString();  // 格式化日期
  }
  return value;
};
</script>

<style scoped>
h3 {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.el-table {
  margin-top: 20px;
  width: 100%;
  table-layout: fixed;
}

.el-table th,
.el-table td {
  text-align: center;
}

.el-button {
  margin-right: 10px;
}

.company-details {
  padding: 10px 20px;
}

.detail-row {
  margin-bottom: 12px;
}

.detail-label {
  font-weight: bold;
}

.el-col {
  padding: 4px;
}
</style>
